<!doctype html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>WebSocket++ Broadcast Admin</title>
    <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="flot/excanvas.min.js"></script><![endif]-->
    <script language="javascript" type="text/javascript" src="vendor/flot/jquery.js"></script>
    <script language="javascript" type="text/javascript" src="vendor/flot/jquery.flot.js"></script>
    <script language="javascript" type="text/javascript" src="vendor/md5.js"></script>
</head>
<body>

<script type="text/javascript">
var options = {"console_enabled": true};

var ws_client;
var ws_admin;
var url;

var data2 = [], total_points = 240;
var stale_data = null;
   
var message_history = [];
var ack_history = [];
var client_history = [];

var msgs = {};

function connect() {
    url = document.getElementById("server_url").value;
    
    if ("WebSocket" in window) {
        ws_client = new WebSocket(url);
        ws_admin = new WebSocket(url+"/admin");
    } else if ("MozWebSocket" in window) {
        ws_client = new MozWebSocket(url);
        ws_admin = new MozWebSocket(url+"/admin");
    } else {
        $("#messages").innerHTML += "This Browser does not support WebSockets<br />";
        return;
    }
    
    ws_client.onopen = function(e) {
        $("#messages").append("Client: A client connection to "+url+" has been opened.<br />");
        
        $("#server_url").disabled = true;
        $("#toggle_connect").html("Disconnect");
    };
    
    ws_admin.onopen = function(e) {
        $("#messages").append("Client: An admin connection to "+url+"/admin has been opened.<br />");
        
        $("#server_url").disabled = true;
        $("#toggle_connect").html("Disconnect");
    };
    
    ws_client.onerror = function(e) {
        $("#messages").append("Client: An error occured on the client channel, see console log for more details.<br />");
        console.log(e);
    };
    ws_admin.onerror = function(e) {
        $("#messages").append("Client: An error occured on the admin channel, see console log for more details.<br />");
        console.log(e);
    };
    
    ws_client.onclose = function(e) {
        $("#messages").append("Client: The client connection to "+url+" was closed.<br />");
        clear_hud();
    };
    
    ws_admin.onclose = function(e) {
        $("#messages").append("Client: The admin connection to "+url+"/admin was closed.<br />");
        clear_hud();
    };
    
    ws_client.onmessage = function(e) {
        if (options.console_enabled) {
            if (e.data.length <= 126) {
                $("#messages").append("Broadcasted Message: "+e.data+"<br />");
            } else {
                $("#messages").append("Broadcasted Message: [message of size: "+e.data.length+"]<br />");
            }
        }
        ws_client.send("ack:"+hex_md5(e.data)+"=1;");
    }
    
    ws_admin.onmessage = function(e) {
        foo = JSON.parse(e.data);
        
        if (foo.type == "message") {
            if (options.console_enabled) {
                document.getElementById("messages").innerHTML += "Broadcasted Message: "+foo.value+"<br />";
            }
        } else if (foo.type == "error") {
            if (options.console_enabled) {
                document.getElementById("messages").innerHTML += "Command Error: "+foo.value+"<br />";
            }
        } else if (foo.type == "con") {
            document.getElementById("connected_clients").innerHTML = foo.value;
        } else if (foo.type == "stats") {
            var msg_delta = 0;
            var data_delta = 0;
            
            for (var i in foo.messages) {
                var hash = foo.messages[i].hash;
                
                if (hash in msgs) {
                    msg_delta += foo.messages[i].acked-msgs[hash]["acked"];
                    data_delta += msg_delta*foo.messages[i].size;
                    
                    msgs[hash]["sent"] = foo.messages[i].sent;
                    msgs[hash]["acked"] = foo.messages[i].acked;
                    msgs[hash]["time"] = foo.messages[i].time;
                } else {
                    msgs[hash] = {"id":foo.messages[i].id,
                                  "sent":foo.messages[i].sent,
                                  "acked":foo.messages[i].acked,
                                  "size":foo.messages[i].size,
                                  "time":foo.messages[i].time}
                    msg_delta += foo.messages[i].acked;
                    data_delta += msg_delta*foo.messages[i].size;
                }
            }
            
            var o = "";
            
            for (i in msgs) {
                o += "<tr><td>"+msgs[i].id+"</td><td>"+msgs[i].sent+"</td><td>"+msgs[i].acked+"</td><td>"+format_data(msgs[i].size)+"</td><td>"+msgs[i].time+"</td><td>"+(msgs[i].time != 0 ? (msgs[i].acked/(msgs[i].time/1000.0)).toFixed(0)+"/s" : "")+"</td><td>"+(msgs[i].time != 0 ? format_data(msgs[i].acked*msgs[i].size/(msgs[i].time/1000.0))+"/s" : "")+"</td></tr>";
            }
            
            $("#sent_messages").html(o);
            
            /*document.getElementById("messages_per_sec").innerHTML = foo.messages+"/s";
            document.getElementById("bytes_per_sec").innerHTML = format_data(foo.bytes)+"/s";
            document.getElementById("messages_sent").innerHTML = foo.messages_sent;
            document.getElementById("messages_acked").innerHTML = foo.messages_acked;
            document.getElementById("bytes_sent").innerHTML = format_data(foo.bytes_sent);*/
            
            
            document.getElementById("admin_connections").innerHTML = foo.admin_connections;
            document.getElementById("connected_clients").innerHTML = foo.connections;
            
            client_history.push([foo.timestamp,foo.connections]);
            if (client_history.length > total_points) {
                client_history = client_history.slice(client_history.length-total_points);
            }
            
            
            data2.push([foo.timestamp,data_delta]);
            if (data2.length > total_points) {
                data2 = data2.slice(data2.length-total_points);
            }
            
            message_history.push([foo.timestamp,msg_delta]);
            if (message_history.length > total_points) {
                message_history = message_history.slice(message_history.length-total_points);
            }
        } else {
            document.getElementById("messages").innerHTML += "Unrecognized Server Command.<br />";
        }
    }
}

function clear_hud() {
    document.getElementById("server_url").disabled = false;
    document.getElementById("toggle_connect").innerHTML = "Connect";
    document.getElementById("connected_clients").innerHTML = "N/A";
    document.getElementById("admin_connections").innerHTML = "N/A";
    document.getElementById("messages_per_sec").innerHTML = "N/A";
    document.getElementById("bytes_per_sec").innerHTML = "N/A";
    document.getElementById("messages_sent").innerHTML = "N/A";
    document.getElementById("bytes_sent").innerHTML = "N/A";
    document.getElementById("messages_acked").innerHTML = "N/A";
}
    
function disconnect() {
    ws_client.close();
    ws_admin.close();
}

function toggle_connect() {
    if (document.getElementById("server_url").disabled === false) {
        connect();
    } else {
        disconnect();
    }
}

function broadcast() {
    if (ws_client === undefined || ws_client.readyState != 1) {
        $("#messages").append("Client: Client websocket is not avaliable for writing<br />");
        return;
    }
    
    ws_client.send(document.getElementById("msg").value);
    document.getElementById("msg").value = "";
}

function send_command(command,args) {
    var cmd = command+":";
    
    ws_admin.send(cmd);
}

function send_test_message(size,type) {
    ws_client.send((new Array(size+1)).join("*"));
}

function format_data(val) {
    if (val > 1000000)
        return (val / 1000000).toFixed(2) + " MB";
    else if (val > 1000)
        return (val / 1000).toFixed(2) + " kB";
    else
        return val.toFixed(0) + " B";
}

$(function () {
    // setup control widget
    var updateInterval = 500;
    $("#updateInterval").val(updateInterval).change(function () {
        var v = $(this).val();
        if (v && !isNaN(+v)) {
            updateInterval = +v;
            if (updateInterval < 1)
                updateInterval = 1;
            if (updateInterval > 2000)
                updateInterval = 2000;
            $(this).val("" + updateInterval);
        }
    });
    
    function suffixFormatter(val, axis) {
        if (val > 1000000)
            return (val / 1000000).toFixed(axis.tickDecimals) + " MB";
        else if (val > 1000)
            return (val / 1000).toFixed(axis.tickDecimals) + " kB";
        else
            return val.toFixed(axis.tickDecimals) + " B";
    }
  
    // setup plot
    var options = {
        series: { shadowSize: 0 }, // drawing is faster without shadows
        xaxis: { mode: "time" }
    };
    
    var options_data = {
        series: { shadowSize: 0 }, // drawing is faster without shadows
        yaxis: { tickFormatter: suffixFormatter},
        xaxis: { mode: "time" }
    };
    
    var plot_clients = $.plot($("#client_history"), [ client_history ], options);
    var plot_messages = $.plot($("#message_history"), [ message_history ], options);
    var plot_bytes = $.plot($("#bytes_history"), [ data2 ], options_data);

    function update() {
        plot_clients.setData([ client_history ]);
        plot_clients.setupGrid();
        plot_clients.draw();
        
        plot_messages.setData([ message_history ]);
        plot_messages.setupGrid();
        plot_messages.draw();
        
        plot_bytes.setData([ data2 ]);
        plot_bytes.setupGrid();
        plot_bytes.draw();

        setTimeout(update, updateInterval);
    }

    update();
});

</script>

<style>
body,html {
    margin: 0px;
    padding: 0px;
    height:100%; 
    font-family: sans-serif;
    font-size: 12px;
}
#controls {
    float:right;
    background-color: #333;
    color: #fff;
    padding: 5px;
}
#controls h2 {
    font-family: sans-serif;
    font-size: 16px;
    margin-bottom: 4px;
}
#controls h3 {
    font-family: sans-serif;
    font-size: 14px;
    margin-bottom: 4px;
}
#messages {
    height: 100%;
    overflow: scroll;
}

</style>

<div id="controls">
    <div id="server">
    <input type="text" name="server_url" id="server_url" value="ws://localhost:9002" />
    <button id="toggle_connect" onclick="toggle_connect();">Connect</button>
    </div>

    <div id="message_input"><input type="text" name="msg" id="msg" value="Hello World!" />
    <button onclick="broadcast();">Broadcast</button></div>
    
    <h2>Stats</h2>
    <h3>Server</h3>
    <div>Connected Clients: <span id="connected_clients">N/A</span><br /></div>
    <div>Admin Clients: <span id="admin_connections">N/A</span><br /></div>
    <div id="client_history" style="width:320px;height:200px;"></div>
    <h3>Messages</h3>
    <div>Messages Sent: <span id="messages_sent">N/A</span><br /></div>
    <div>Messages Acked: <span id="messages_acked">N/A</span><br /></div>
    <div>Messages Rate: <span id="messages_per_sec">N/A</span><br /></div>
    <div id="message_history" style="width:320px;height:200px;"></div>
    
    <div>
        <table>
            <thead>
                <tr><th>id</th><th>sent</th><th>acked</th><th>size</th><th>time</th><th>message rate</th><th>data rate</th></tr>
            </thead>
            <tbody id="sent_messages">
            </tbody>
        </table>
    </div>
    
    <h3>Data</h3>
    <div>Bytes Sent: <span id="bytes_sent">N/A</span><br /></div>
    <div>Data Rate: <span id="bytes_per_sec">N/A</span><br /></div>
    <div id="bytes_history" style="width:320px;height:200px;"></div>
</div>
<div id="messages"></div>

</body>
</html>